/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package it.polimi.deib.se2.meteocal.business.boundary;

import it.polimi.deib.se2.meteocal.business.entity.Event;
import it.polimi.deib.se2.meteocal.business.entity.User;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.joda.time.DateTime;

@Stateless
public class EventManager {
    
    @PersistenceContext
            EntityManager em;
    
    @Inject
            Principal principal;
    
    public void save(Event event) {
        em.persist(event);
    }
    
    public Event getEvent() {
        return em.find(Event.class, principal.getName());
    }
    
    public void remove(Event event){
        em.remove(em.merge(event));
    }
    
    public Event find(Long id) {
        return em.find(Event.class, id);
    }
    public void edit(Event event) {
        em.merge(event);
    }
    
    public List<Event> findAllEventsIn3Days(User user){
        Date today = new Date();
        DateTime todayDT = new DateTime(today);
        Date inThreeDays = todayDT.plusDays(3).toDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(inThreeDays);
        
        Query q = em.createNativeQuery("SELECT * FROM meteocaldb.EVENTS WHERE (STARTDATE<=\""+date+"\" AND creator=\""+user.getEmail()+"\")",Event.class);
        return q.getResultList();
    }
    
    public List<Event> getEventsByUser(User loggedUser) {
        Query q = em.createNativeQuery("SELECT * FROM meteocaldb.EVENTS WHERE creator=\""+loggedUser.getEmail()+"\"",Event.class);
        return q.getResultList();    }
}
